package taskadvanced.ui.handlers;

import java.net.URL;

import org.eclipse.core.commands.AbstractHandler;
import org.eclipse.core.commands.ExecutionEvent;
import org.eclipse.core.commands.ExecutionException;
import org.eclipse.jface.preference.IPreferenceStore;
import org.eclipse.ui.IWorkbenchWindow;
import org.eclipse.ui.PartInitException;
import org.eclipse.ui.browser.IWebBrowser;
import org.eclipse.ui.browser.IWorkbenchBrowserSupport;
import org.eclipse.ui.handlers.HandlerUtil;

import taskadvanced.Activator;
import taskadvanced.core.rtm.Service;
import taskadvanced.core.rtm.Setup;
import taskadvanced.preferences.PreferenceConstants;

/**
 * Show a web page in a browser
 */
public class OpenWebPageHandler extends AbstractHandler {
	public Object execute(ExecutionEvent event) throws ExecutionException {
		Service service = new Service();
		
		if (!service.isAuthorized()) {
			String token = service.getToken();
			if (token.length() > 0) {
				IPreferenceStore prefs = Activator.getDefault().getPreferenceStore();
				prefs.setValue(PreferenceConstants.AUTH_TOKEN, token);
				System.out.println("auth_token:"+token);
			}
			else {
				IWorkbenchWindow window = HandlerUtil.getActiveWorkbenchWindow(event);
				IWorkbenchBrowserSupport browserSupport = window.getWorkbench().getBrowserSupport();
				
				URL webUrl = service.getAuthURL();
				IWebBrowser browser;
				try {
					browser = browserSupport.createBrowser(
							IWorkbenchBrowserSupport.AS_EDITOR, null,
							"Login to Remember the Milk", "Login to Remember the Milk");
					browser.openURL(webUrl);
				} catch (PartInitException e) {
					e.printStackTrace();
					return null;
				}	
			}
		}
		else{
			System.out.println("authorized already!");
			Setup setup = new Setup(service);
			setup.initialize();
			
		}

		return null;
	}
}
